﻿using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using Xpedite.Localization;
using Xpedite.Resources;
using Xpedite.Resources.Combiners;
using Xpedite.Resources.Definitions;

/* Copyright (c) 2010 CBaxter
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), 
 * to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, 
 * and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS 
 * IN THE SOFTWARE. 
 */

namespace Xpedite.Test.Resources.Combiners
{
  [TestClass]
  public class SpriteCssCombinerTest
  {
    private readonly Mock<IResourceDefinition> _resourceDefinition = new Mock<IResourceDefinition>(MockBehavior.Strict);
    private readonly Mock<IResourceUrl> _virtualUrl = new Mock<IResourceUrl>(MockBehavior.Strict);

    public SpriteCssCombinerTest()
    {
      _resourceDefinition.SetupGet(mock => mock.ResourceType).Returns(ResourceType.Png);
      _resourceDefinition.SetupGet(mock => mock.ReferenceName).Returns("Composite-Resource");
      _virtualUrl.SetupGet(mock => mock.VirtualPath).Returns("/combined.xcr");
    }

    [TestMethod]
    public void TestCombineWithNoResourcesDefined()
    {
      _resourceDefinition.SetupGet(mock => mock.Resources).Returns(new IResourceContainer[0]);
      _resourceDefinition.SetupGet(mock => mock.References).Returns(new INamedValue<IResourceContainer>[0]);

      var container = new SpriteCssCombiner().Combine(_virtualUrl.Object, _resourceDefinition.Object);
      
      Expect.Exception(() => container.Resource, new XpediteException(String.Format(ExceptionMessages.AtLeastOneResourceRequired, "Composite-Resource")));
    }

    [TestMethod]
    public void TestCombineWithSingleResourcesDefined()
    {
      var containers = new[] { 
        BuildImageResource(ResourceType.Png, ImageFormat.Png, DateTime.UtcNow.Date.AddDays(-7), new Size(10, 10)) 
      };
      
      _resourceDefinition.SetupGet(mock => mock.Resources).Returns(containers);
      _resourceDefinition.SetupGet(mock => mock.References).Returns(new INamedValue<IResourceContainer>[] { NamedValue.Create("Resource1", containers[0]) });

      var container = new SpriteCssCombiner().Combine(_virtualUrl.Object, _resourceDefinition.Object);
      var resource = container.Resource;

      Assert.AreEqual(ResourceType.Css, container.ResourceType);
      Assert.AreEqual(_virtualUrl.Object, container.ResourceUrl);

      Assert.IsTrue(resource.Compressable);
      Assert.AreEqual(ResourceType.Css, resource.Type);
      Assert.AreEqual(Encoding.UTF8, resource.Encoding);
      Assert.AreEqual(DateTime.UtcNow.Date.AddDays(-7), resource.LastModified);
      Assert.AreEqual(
        ".xpedite-png-Composite-Resource{margin:0;padding:0,border:0 solid transparent;background-image:url('/combined.xcr');}.xpedite-png-Composite-Resource.Resource1{background-position:0 0;}",
        Encoding.UTF8.GetString(resource.Bytes)
      );
    }

    [TestMethod]
    public void TestCombineWithMultipleLikeResourcesDefined()
    {
      var containers = new[] { 
        BuildImageResource(ResourceType.Png, ImageFormat.Png, DateTime.UtcNow.Date.AddDays(-7), new Size(10, 10)),
        BuildImageResource(ResourceType.Png, ImageFormat.Png, DateTime.UtcNow.Date.AddDays(-14), new Size(10, 10)),
        BuildImageResource(ResourceType.Png, ImageFormat.Png, DateTime.UtcNow.Date.AddDays(-14), new Size(20, 10)),
        BuildImageResource(ResourceType.Png, ImageFormat.Png, DateTime.UtcNow.Date.AddDays(-14), new Size(30, 10)),
        BuildImageResource(ResourceType.Png, ImageFormat.Png, DateTime.UtcNow.Date.AddDays(-14), new Size(30, 10)) 
      };

      _resourceDefinition.SetupGet(mock => mock.Resources).Returns(containers);
      _resourceDefinition.SetupGet(mock => mock.References).Returns(new INamedValue<IResourceContainer>[] { 
        NamedValue.Create("Resource1", containers[0]),
        NamedValue.Create("Resource2", containers[1]),
        NamedValue.Create("Resource2", containers[2]),
        NamedValue.Create("Resource2", containers[3]),
        NamedValue.Create("Resource2", containers[4]) 
      });

      var container = new SpriteCssCombiner().Combine(_virtualUrl.Object, _resourceDefinition.Object);
      var resource = container.Resource;

      Assert.AreEqual(ResourceType.Css, container.ResourceType);
      Assert.AreEqual(_virtualUrl.Object, container.ResourceUrl);

      Assert.IsTrue(resource.Compressable);
      Assert.AreEqual(ResourceType.Css, resource.Type);
      Assert.AreEqual(Encoding.UTF8, resource.Encoding);
      Assert.AreEqual(DateTime.UtcNow.Date.AddDays(-14), resource.LastModified);
      Assert.AreEqual(
        ".xpedite-png-Composite-Resource{margin:0;padding:0,border:0 solid transparent;background-image:url('/combined.xcr');}.xpedite-png-Composite-Resource.Resource1{background-position:0 0;}.xpedite-png-Composite-Resource.Resource2{background-position:-10px 0;}.xpedite-png-Composite-Resource.Resource2{background-position:-20px 0;}.xpedite-png-Composite-Resource.Resource2{background-position:-40px 0;}.xpedite-png-Composite-Resource.Resource2{background-position:-70px 0;}",
        Encoding.UTF8.GetString(resource.Bytes)
      );
    }

    [TestMethod]
    public void TestCombineWithMultipleResourcesDefinedWithDifferingTypes()
    {
      var containers = new[] { 
        BuildImageResource(ResourceType.Png, ImageFormat.Png, DateTime.UtcNow.Date.AddDays(-7), new Size(10, 10)),
        BuildImageResource(ResourceType.Gif, ImageFormat.Gif, DateTime.UtcNow.Date.AddDays(-14), new Size(10, 10))
      };

      _resourceDefinition.SetupGet(mock => mock.Resources).Returns(containers);
      _resourceDefinition.SetupGet(mock => mock.References).Returns(new INamedValue<IResourceContainer>[] { 
        NamedValue.Create("Resource1", containers[0]),
        NamedValue.Create("Resource2", containers[1])
      });

      var container = new SpriteCssCombiner().Combine(_virtualUrl.Object, _resourceDefinition.Object);
      var resource = container.Resource;

      Assert.AreEqual(ResourceType.Css, container.ResourceType);
      Assert.AreEqual(_virtualUrl.Object, container.ResourceUrl);

      Assert.IsTrue(resource.Compressable);
      Assert.AreEqual(ResourceType.Css, resource.Type);
      Assert.AreEqual(Encoding.UTF8, resource.Encoding);
      Assert.AreEqual(DateTime.UtcNow.Date.AddDays(-14), resource.LastModified);
      Assert.AreEqual(
        ".xpedite-png-Composite-Resource{margin:0;padding:0,border:0 solid transparent;background-image:url('/combined.xcr');}.xpedite-png-Composite-Resource.Resource1{background-position:0 0;}.xpedite-png-Composite-Resource.Resource2{background-position:-10px 0;}",
        Encoding.UTF8.GetString(resource.Bytes)
      );
    }
    
    [TestMethod]
    public void TestCombineWithMultipleResourcesDefinedWithNonImageResource()
    {
      var containers = new[] { 
        BuildImageResource(ResourceType.Png, ImageFormat.Png, DateTime.UtcNow.Date.AddDays(-7), new Size(10, 10)),
        BuildResource(ResourceType.Css, Encoding.UTF8, "css Content", DateTime.UtcNow.Date.AddDays(-14), true)
      };

      _resourceDefinition.SetupGet(mock => mock.Resources).Returns(containers);
      _resourceDefinition.SetupGet(mock => mock.References).Returns(new INamedValue<IResourceContainer>[] { 
        NamedValue.Create("Resource1", containers[0]),
        NamedValue.Create("Resource2", containers[1])
      });

      var container = new SpriteCssCombiner().Combine(_virtualUrl.Object, _resourceDefinition.Object);
      var resource = container.Resource;

      Assert.AreEqual(ResourceType.Css, container.ResourceType);
      Assert.AreEqual(_virtualUrl.Object, container.ResourceUrl);

      Assert.IsTrue(resource.Compressable);
      Assert.AreEqual(ResourceType.Css, resource.Type);
      Assert.AreEqual(Encoding.UTF8, resource.Encoding);
      Assert.AreEqual(DateTime.UtcNow.Date.AddDays(-7), resource.LastModified);
      Assert.AreEqual(
        ".xpedite-png-Composite-Resource{margin:0;padding:0,border:0 solid transparent;background-image:url('/combined.xcr');}.xpedite-png-Composite-Resource.Resource1{background-position:0 0;}",
        Encoding.UTF8.GetString(resource.Bytes)
      );
    }

    private static IResourceContainer BuildImageResource(ResourceType resourceType, ImageFormat imageFormat, DateTime lastModified, Size size)
    {
      Byte[] bytes;

      var resource = new Mock<IImageResource>(MockBehavior.Strict);

      using (var memoryStream = new MemoryStream())
      {
        using (var image = new Bitmap(size.Width, size.Height))
          image.Save(memoryStream, imageFormat);

        bytes = memoryStream.ToArray();
      }

      resource.SetupGet(mock => mock.Bytes).Returns(bytes);
      resource.SetupGet(mock => mock.LastModified).Returns(lastModified);
      resource.SetupGet(mock => mock.Encoding).Returns(Encoding.UTF8);
      resource.SetupGet(mock => mock.Compressable).Returns(false);
      resource.SetupGet(mock => mock.Type).Returns(resourceType);
      resource.SetupGet(mock => mock.Size).Returns(size);

      var container = new Mock<IResourceContainer>(MockBehavior.Strict);

      container.SetupGet(mock => mock.Resource).Returns(resource.Object);
      container.SetupGet(mock => mock.ResourceType).Returns(resourceType);

      return container.Object;
    }

    private static IResourceContainer BuildResource(ResourceType resourceType, Encoding encoding, String content, DateTime lastModified, Boolean compressable)
    {
      var resource = new Mock<IResource>(MockBehavior.Strict);

      resource.SetupGet(mock => mock.Bytes).Returns(encoding.GetBytes(content));
      resource.SetupGet(mock => mock.LastModified).Returns(lastModified);
      resource.SetupGet(mock => mock.Compressable).Returns(compressable);
      resource.SetupGet(mock => mock.Encoding).Returns(encoding);
      resource.SetupGet(mock => mock.Type).Returns(resourceType);

      var container = new Mock<IResourceContainer>(MockBehavior.Strict);

      container.SetupGet(mock => mock.Resource).Returns(resource.Object);
      container.SetupGet(mock => mock.ResourceType).Returns(resourceType);

      return container.Object;
    }
  }
}
